function stringFormat(str, arr) {
    return str.replace(/\{(\d+)\}/g, function(src, $1) {
		return arr[$1];
	});
}

try {
    window.barrageArr = [],
    window.barrageAll = [];

    var Barrage = {
        left: document.documentElement.clientWidth,
        translateX: document.documentElement.clientWidth || 0,
        fontSize: "12",
        color: "#000",
        top: ["10px", "40px", "70px"],
        init_time: document.documentElement.clientWidth / 50,
        interval_time: 2800,
        barrageAdd: [],
        timeCacluate: null,
        barrageState: document.getElementsByName("barrage_state").length > 0 ? document.getElementsByName("barrage_state")[0].value : 1,
        danMuPlay: function(data) {
            if (typeof(data) != "underined") {
                var _this = this;

                if (parseInt(_this.barrageState) != 0) {
                    var remaind = 0,
    					flag = false;

                    _this.interval_time = Math.min(1000 * _this.init_time / 2, 4200);
                    _this.timeCacluate = setInterval(function(arr) {
						var htmlTpl1 = '<li data-type="{0}" data-mid="{1}" data-name="{2}" style="background-color:rgba(18,155,240,.78);position: absolute;left:{3}px;top:{4};display: inline-block;white-space: pre;">';
						var htmlTpl2 = '<li data-type="{0}" data-mid="{1}" data-name="{2}" style="position: absolute;left:{3}px;top:{4};display: inline-block;white-space: pre;">';
						var tplArray = [];

                        for (var htmlArray = [], i = 0; i < _this.top.length && arr.length > 0; i++) {
							tplArray.length = 0;	// 清空数组

							tplArray.push(arr[0].type);
							tplArray.push(arr[0].source_id);
							tplArray.push(arr[0].user_name);
							tplArray.push(_this.left);
							tplArray.push(_this.top[i]);

                            if (arr[0].prop_img != "") {
                                var color = _this.colorRandom();
                                console.log(color);

                                htmlArray.push(stringFormat(htmlTpl1, tplArray));
                                htmlArray.push('<img src="' + arr[0].img + '" alt="" />');
                                htmlArray.push("<span>" + arr[0].content + "</span>");

                                if (typeof(arr[0].prop_img) != "undefined") {
									htmlArray.push('<img src="' + arr[0].prop_img + '" style="width: 40px;margin: -16px 0 0 10px;vertical-align: -13px">');
                                }
                                htmlArray.push("</li>");
                            } else {
								htmlArray.push(stringFormat(htmlTpl2, tplArray));
							}

                            htmlArray.push('<img src="' + arr[0].img + '" alt="" />');
                            htmlArray.push("<span>" + arr[0].content + "</span>");
                            htmlArray.push("</li>");

                            arr.shift();
                        }

                        if (!$(".j_barrage").hasClass("hide")) {
							$(".j_barrage").find("ul").append(htmlArray.join(""));
						}

                        var itemWidth = 0;
						var length = $(".j_barrage").find("ul").children().length;
                        
						if (length > 300) {
							$(".j_barrage").find("ul").html("");
						}

                        for (var i = 0; i < length;) {
							for (var k = 0; k < _this.top.length && i < length; k++) {
								itemWidth = $(".j_barrage").find("li").eq(i).width();
								remaind = itemWidth / 500;

								$(".j_barrage").find("li").eq(i).css({
									"transform": "translateX(-" + (_this.left + itemWidth + 170) + "px)",
									"-webkit-transform": "translateX(-" + (_this.left + itemWidth + 170) + "px)",
									"left": "" + _this.left + "px",
									"transition": "transform " + (_this.init_time + remaind) + "s linear",
									"-webkit-transition": "-webkit-transform " + (_this.init_time + remaind) + "s linear"
								});

								i++;
							}
						}

                        if (arr.length == 0) {
							if (_this.barrageAdd.length == 0) {
								flag = false;
								clearInterval(_this.timeCacluate);
								_this.timeCacluate = null;

								var dataArray = [];
								$.extend(dataArray, barrageAll);

								console.log("-----circle queue------");
								_this.danMuPlay(dataArray);
							} else {
								if (flag) {
									return;
								}

								flag = true;
								clearInterval(_this.timeCacluate);
								_this.timeCacluate = null;

								console.log("-----cache queue------");
								_this.danMuPlay(_this.barrageAdd);
							}
						}
                    }.bind(_this, data), _this.interval_time);

                    _this.danMuClear();
                }
            }
        },
        danMuInsert: function(dataArray, params) {
            var _this = this,
				defaultImg = "http://tva1.sinaimg.cn/default/images/default_avatar_male_50.gif",
				defaultUsr = "用户";

            if (typeof(userInfo) != "undefined") {
				defaultImg = userInfo.userface;
				defaultUsr = userInfo.uname;
            }

            setTimeout(function() {
                dataArray.unshift({
                    user_name: defaultUsr,
                    img: defaultImg,
                    content: params.content,
                    type: "2",
                    source_id: "",
                    prop_img: params.prop_img
                });

                clearInterval(_this.timeCacluate);
                _this.timeCacluate = null;

                console.log("-----insert queue------");
                _this.danMuPlay(dataArray);
            }, 2000);
        },
        danMuAdd: function(dataArray) {
            var _this = this;
            _this.barrageAdd = _this.barrageAdd.concat(dataArray);
        },
        danMuClear: function() {
            setInterval(function() {
				var $children = $(".j_barrage").find("ul").children();
                for (var i = 0; i < $children.length; i++) {
					if ($children.eq(i).offset().left < -190) {
						$children.eq(i).remove();
					}
				}
            }, 1000);
        },
        colorRandom: function() {
            var alpha = 0.78;
			var colors = [
				"rgba(141,50,160," + alpha + ")",
				"rgba(225,99,15," + alpha + ")",
				"rgba(242,73,73," + alpha + ")",
				"rgba(18,155,240," + alpha + ")",
				"rgba(90,162,12," + alpha + ")",
				"rgba(20,185,148," + alpha + ")"
			];
			var rndIndex = Math.floor(Math.random() * colors.length);

            return colors[rndIndex];
        }
    };
    $(function() {
        function danMuPlay(dataArray) {
            $(".j_barrage").removeClass("hide");

			var dataItem;
            for (var i = 0; i < dataArray.length; i++) {
				dataItem = dataArray[i];
				barrageArr.push({
					user_name: dataItem.user_name || "",
					img: dataItem.user_face || "http://n.sinaimg.cn/mobileh5/01345b8f/20160802/default.jpg",
					content: dataItem.content,
					type: dataItem.type,
					source_id: dataItem.source_id,
					prop_img: ""
				});
			}

            $.extend(barrageAll, barrageArr);
            console.log("-----start queue------");
            Barrage.danMuPlay(barrageArr);
        }

        $(".foot_barr").on("click", function() {
			var $this = $(this);

            if ($this.hasClass("foot_barr_active")) {
				$(".j_barrage").removeClass("hide");
				$(".j_barrage ul").children().remove();
				$this.removeClass("foot_barr_active");
            } else {
				$this.addClass("foot_barr_active");
				$(".j_barrage").addClass("hide");
			}
        });

        var url = document.getElementsByName("barrage")[0].value;
        $.ajax({
            url: url,
            type: "GET",
            timeout: 10000,
            success: function(rs) {
                if (rs.errno && rs.data.length > 0) {
					danMuPlay(rs.data);
                }
            },
            error: function(msg) {
                alert("您的网络不给力,请点击重试!");
            }
        });
        $(".j_barrage").on("click", function(evt) {
            var target = evt.target;
			var params = {
				parent: "",
				name: ""
			};
			var $lis = $(target).parents("li");
			var dataType = parseInt($lis.data("type"));

			if (dataType == 2) {
				params.parent = $lis.data("mid");
				params.name = $lis.data("name");
			}

            if (checkLogin()) {
                //userInfo.uid;
                window.cmtInputShow("barrage", "", "", "", params);
            } else {
                var instance = typeof(WapLogin) == "function" ? (new WapLogin) : this;
                instance.login(false, function(evt) {
                    //userInfo.uid;
                    window.cmtInputShow("barrage", "", "", "", params);
                });
            }
        })
    })
} catch(e) {
    console["error" in console ? "error" : "log"](e, "barrage.js");
}